/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

(function ($, document, undefined) {
    var design = function () {
    };

    design.prototype = {
        version: "1.0",
        author: "uybv.cntt",
        loaded: false,
        change: false,
        dom: {
            wrap: undefined,
            productTool: undefined,
            itemTool: undefined,
            canvas: undefined,
            draw: undefined,
            btnProduct: undefined,
            btnItem: undefined,
            btnText: undefined,
            btnUpload: undefined,
            proInfo: undefined,
            proTool: undefined,
            btnAddCart: undefined
        },
        template: {
            text: undefined,
            itemImg: undefined,
            listItem: undefined,
            listProduct: undefined,
            proSize: undefined,
            proColor: undefined,
            proView: undefined,
            canvas: undefined
        },
        currentData: undefined,
        init: function (wrap) {
            var that = this;

            /* Khởi tạo DOM */

            that.dom.wrap = wrap;
            that.dom.productTool = that.dom.wrap.find("#product-tool").first();
            that.dom.itemTool = that.dom.wrap.find("#item-tool").first();
            that.dom.canvas = that.dom.wrap.find("#design-canvas").first();
            that.dom.draw = function () {
                return that.dom.canvas.find(".design-panel.active").first();
            };
            that.dom.btnProduct = that.dom.wrap.find("#btn-product").first();
            that.dom.btnItem = that.dom.wrap.find("#btn-item").first();
            that.dom.btnText = that.dom.wrap.find("#btn-text").first();
            that.dom.btnUpload = that.dom.wrap.find("#btn-upload").first();
            that.dom.proInfo = that.dom.wrap.find("#design-properties").first();
            that.dom.proTool = that.dom.wrap.find("#pro-tool").first();
            that.dom.btnAddCart = that.dom.wrap.find("#btn-add-cart").first();

            that.template.text = kendo.template($("#textTemplate").html());
            that.template.itemImg = kendo.template($("#itemTemplate").html());
            that.template.listItem = kendo.template($("#list-item-template").html());
            that.template.listProduct = kendo.template($("#list-product-template").html());
            that.template.proSize = kendo.template($("#pro-size-template").html());
            that.template.proColor = kendo.template($("#pro-color-template").html());
            that.template.proView = kendo.template($("#pro-view-template").html());
            that.template.canvas = kendo.template($("#canvas-template").html());


            that.dom.proTool.find("#pro-font-color").ColorPicker({
                color: '#000000',
                onShow: function (colpkr) {
                    $(colpkr).fadeIn(100);
                    return false;
                },
                onHide: function (colpkr) {
                    $(colpkr).fadeOut(100);
                    return false;
                },
                onChange: function (hsb, hex, rgb) {
                    that.dom.proTool.find("#pro-font-color").children("div").css('backgroundColor', '#' + hex);

                    var input = that.dom.canvas.find(".design-panel.active").first()
                            .find(".import-text.active").first()
                            .find("textarea").first();

                    input.css({
                        "color": "#" + hex
                    });
                    input.attr("data-color", "#" + hex);
                }
            });

            /* Tạo event */

            that.dom.productTool.delegate("form", "submit", function (e) {
                e.preventDefault();

                $(this).ajaxSubmit({
                    dataType: "json",
                    success: function (response) {
                        that.dom.productTool.find(".info").html(response.current + "/" + response.total);
                        that.dom.productTool.find("ul").empty().append(kendo.render(that.template.listProduct, response.data));
                        that.dom.productTool.find("form > input[name='page']").attr("max", response.total);
                        if (that.loaded === false) {
                            that.dom.productTool.find("a.img-product").first().click();
                            that.loaded = true;
                        }
                    }
                });
            });

            that.dom.productTool.delegate(".btn-prev", "click", function (e) {
                e.preventDefault();
                var pageEl = that.dom.productTool.find("form > input[name='page']").first();
                var page = parseInt(pageEl.val());
                if (page > 1) {
                    page--;
                }
                pageEl.val(page);
                that.dom.productTool.find("form").submit();
            });

            that.dom.productTool.delegate(".btn-next", "click", function (e) {
                e.preventDefault();
                var pageEl = that.dom.productTool.find("form > input[name='page']").first();
                var page = parseInt(pageEl.val());
                var max = parseInt(pageEl.attr("max"));
                if (page < max) {
                    page++;
                }
                pageEl.val(page);
                that.dom.productTool.find("form").submit();
            });
            //Call form submit
            that.dom.productTool.delegate(".btn-search", "click", function (e) {
                e.preventDefault();
                that.dom.productTool.find("form").submit();
            });
            that.dom.productTool.delegate("#categoryId", "change", function (e) {
                e.preventDefault();
                that.dom.productTool.find("form").submit();
            });

            that.dom.productTool.delegate(".img-product", "click", function (e) {
                e.preventDefault();

                /*
                 if (that.change == true) {
                 if (confirm("Bạn muốn đổi sang mẫu áo này?") == false) {
                 return false;
                 }
                 }
                 that.change = true;
                 */
                //Price
                var price = parseFloat($(this).attr("price"));
                $('#price').attr("price", price);
                $('#price').text(price.formatMoney(0, ',', '.'));

                that.dom.canvas.empty();
                that.dom.proInfo.find("ul").empty();

                var url = $(this).attr("href");
                var productId = parseInt($(this).attr("data-id"));
                $.ajax({
                    url: url,
                    type: "GET",
                    dataType: "json",
                    data: {
                        id: productId
                    },
                    success: function (response) {
                        if (response.status) {
                            that.currentData = response.data;
                            var objSize = that.dom.proInfo.find("ul.pro-size");
                            objSize.empty();
                            $.each(that.currentData.sizes, function (key, size) {
                                objSize.append(that.template.proSize(size));
                            });

                            var objColor = that.dom.proInfo.find("ul.pro-color");
                            objColor.empty();
                            var setDefault = false;
                            $.each(that.currentData.colors, function (key, color) {
                                objColor.append(that.template.proColor({
                                    color: key,
                                    isActive: (setDefault === false)
                                }));
                                setDefault = true;
                            });
                            objColor.find("li.selected > a").first().click();
                        } else {
                            alert(response.msg);
                        }
                    }
                });
            });

            that.dom.proInfo.delegate("ul.pro-color > li > a", "click", function (e) {
                e.preventDefault();
                that.dom.proInfo.find("ul.pro-color > li").removeClass("selected");
                var liParent = $(this).closest("li");
                liParent.addClass("selected");

                var ulView = that.dom.proInfo.find("ul.pro-type").first();
                var items = ulView.find("li");

                var isCreate = (items.length === 0);
                var color = liParent.attr("data-color");
                $.each(that.currentData.colors[color], function (key, img) {
                    if (isCreate) {
                        ulView.append(that.template.proView({
                            isActive: img.isActive,
                            type: key,
                            url: img.url
                        }));
                        var cv = $("<div>").append(that.template.canvas({
                            url: img.url,
                            type: key
                        })).children();

                        that.dom.canvas.append(cv);
                        if (img.isActive) {
                            cv.addClass("active");
                        }
                    } else {
                        $(items).each(function () {
                            if ($(this).attr("data-type") == key) {
                                $(this).attr("data-url", img.url);
                                $(this).find("img").attr("src", img.url);
                            }
                        });

                        $(that.dom.canvas).find("div").each(function () {
                            if ($(this).attr("data-type") == key) {
                                $(this).children("img").attr("src", img.url);
                            }
                        });
                    }
                });
            });

            that.dom.proInfo.delegate("ul.pro-size > li > a", "click", function (e) {
                e.preventDefault();
                that.dom.proInfo.find("ul.pro-size > li").removeClass("selected");
                $(this).closest("li").addClass("selected");
            });

            that.dom.proInfo.delegate("ul.pro-type > li > a", "click", function (e) {
                e.preventDefault();
                that.dom.proInfo.find("ul.pro-type > li").removeClass("selected");
                $(this).closest("li").addClass("selected");

                that.dom.canvas.children().removeClass("active");
                that.dom.canvas.children("[data-type='" + $(this).closest("li").attr("data-type") + "']").first().addClass("active");

            });

            that.dom.itemTool.delegate("form", "submit", function (e) {
                e.preventDefault();

                $(this).ajaxSubmit({
                    dataType: "json",
                    success: function (response) {
                        that.dom.itemTool.find(".info").html(response.current + "/" + response.total);
                        that.dom.itemTool.find("ul").empty().append(kendo.render(that.template.listItem, response.data));
                        that.dom.itemTool.find("form > input[name='page']").attr("max", response.total);
                    }
                });
            });
            that.dom.itemTool.delegate(".btn-prev", "click", function (e) {
                e.preventDefault();
                var pageEl = that.dom.itemTool.find("form > input[name='page']").first();
                var page = parseInt(pageEl.val());
                if (page > 1) {
                    page--;
                }
                pageEl.val(page);
                that.dom.itemTool.find("form").submit();
            });

            that.dom.itemTool.delegate(".btn-next", "click", function (e) {
                e.preventDefault();
                var pageEl = that.dom.itemTool.find("form > input[name='page']").first();
                var page = parseInt(pageEl.val());
                var max = parseInt(pageEl.attr("max"));
                if (page < max) {
                    page++;
                }
                pageEl.val(page);
                that.dom.itemTool.find("form").submit();
            });
            that.dom.itemTool.delegate(".btn-search", "click", function (e) {
                e.preventDefault();
                that.dom.itemTool.find("form").submit();
            });
            that.dom.itemTool.delegate("#categoryId", "change", function (e) {
                e.preventDefault();
                that.dom.itemTool.find("form").submit();
            });
            that.dom.itemTool.delegate(".img-item", "click", function (e) {
                e.preventDefault();
                //Tính giá khi thêm item
                var curPrice = parseFloat($("#price").attr("price"));
                var itemPrice = parseFloat($(this).attr("price"));
                var price = curPrice + itemPrice;
                $("#price").attr("price", price);
                $("#price").text(price.formatMoney(0, ',', '.'));

                var imgUrl = $(this).attr("data-imgurl");
                var width = $(this).attr("data-width");
                var height = $(this).attr("data-height");
                var price = $(this).attr("price");

                var html = that.template.itemImg({
                    imgUrl: imgUrl,
                    width: width,
                    height: height,
                    price: price
                });
                var obj = $("<div>").html(html).children("div").first();
                if (typeof (that.dom.draw) === "function") {
                    that.dom.draw().append(obj);
                } else {
                    that.dom.draw.append(obj);
                }
                that.itemInitHandle(obj);
            });

            var btnDesignAnimate = function (callback) {
                var currentFocus = that.dom.wrap.find(".design-data.active");
                currentFocus.animate({
                    left: "-280px",
                    opacity: 0
                }, 200, function () {
                    currentFocus.removeClass("active");
                    callback();
                });
            };

            that.dom.btnProduct.on("click", function (e) {
                e.preventDefault();

                if ($(this).hasClass("active")) {
                    return false;
                }

                $(this).addClass("active");
                that.dom.btnItem.removeClass("active");
                that.dom.btnText.removeClass("active");
                that.dom.btnUpload.removeClass("active");

                btnDesignAnimate(function () {
                    that.dom.productTool.addClass("active");
                    that.dom.productTool.animate({
                        left: "12px",
                        opacity: 1
                    }, 200, function () {
                    });
                });
            });

            that.dom.btnItem.on("click", function (e) {
                e.preventDefault();

                if ($(this).hasClass("active")) {
                    return false;
                }

                $(this).addClass("active");
                that.dom.btnProduct.removeClass("active");
                that.dom.btnText.removeClass("active");
                that.dom.btnUpload.removeClass("active");

                btnDesignAnimate(function () {
                    that.dom.itemTool.addClass("active");
                    that.dom.itemTool.animate({
                        left: "12px",
                        opacity: 1
                    }, 200, function () {

                    });
                });
            });

            that.dom.btnText.on("click", function (e) {
                e.preventDefault();
                var html = that.template.text({
                    text: ""
                });
                var obj = $("<div>").html(html).children("div").first();
                if (typeof (that.dom.draw) === "function") {
                    that.dom.draw().append(obj);
                } else {
                    that.dom.draw.append(obj);
                }
                that.textInitHandle(obj);
            });

            that.dom.canvas.on("click", function (e) {
                e.preventDefault();
                if ($(e.target).closest(".import-item").length > 0 && $(e.target).closest(".btn-remove").length === 0) {
                    var item = $(e.target).closest(".import-item").first();
                    $(this).find(".design-panel.active").find(".import-item").removeClass("active");
                    item.addClass("active");
                    if (item.hasClass("import-img")) {
                        that.dom.proTool.find(".pro-tool-item").addClass("hide");
                        that.dom.proTool.find(".pro-tool-img").removeClass("hide");
                    } else if (item.hasClass("import-text")) {
                        that.dom.proTool.find(".pro-tool-item").addClass("hide");
                        that.dom.proTool.find(".pro-tool-text").removeClass("hide");
                        var input = item.find("textarea");
                        that.dom.proTool.find("#pro-font-family").val(input.attr("data-family"));
                        if (input.attr("data-bold") == "1") {
                            that.dom.proTool.find("#pro-font-bold").addClass("active");
                        } else {
                            that.dom.proTool.find("#pro-font-bold").removeClass("active");
                        }
                        if (input.attr("data-italic") == "1") {
                            that.dom.proTool.find("#pro-font-itilic").addClass("active");
                        } else {
                            that.dom.proTool.find("#pro-font-itilic").removeClass("active");
                        }
                        that.dom.proTool.find("#pro-font-size").val(input.attr("data-size"));
                        that.dom.proTool.find("#pro-font-agile-left, #pro-font-agile-center, #pro-font-agile-right").removeClass("active");
                        if (input.attr("data-align") == "0") {
                            that.dom.proTool.find("#pro-font-agile-left").addClass("active");
                        } else if (input.attr("data-align") == "1") {
                            that.dom.proTool.find("#pro-font-agile-center").addClass("active");
                        } else if (input.attr("data-align") == "2") {
                            that.dom.proTool.find("#pro-font-agile-right").addClass("active");
                        }
                        that.dom.proTool.find("#pro-font-color").ColorPickerSetColor(input.attr("data-color"));
                        that.dom.proTool.find("#pro-font-color").children("div").css('backgroundColor', input.attr("data-color"));
                    }
                } else {
                    $(this).find(".design-panel.active").find(".import-item").removeClass("active");
                    that.dom.proTool.find(".pro-tool-img").addClass("hide");
                    that.dom.proTool.find(".pro-tool-text").addClass("hide");
                }
            });

            that.dom.proTool.delegate("#pro-font-family", "change", function (e) {
                var input = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-text.active").first()
                        .find("textarea").first();

                var val = $(this).val();
                input.css({
                    "font-family": val
                });
                input.attr("data-family", val);
            });

            that.dom.proTool.delegate("#pro-font-bold", "click", function (e) {
                e.preventDefault();
                var input = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-text.active").first()
                        .find("textarea").first();
                if ($(this).hasClass("active")) {
                    input.css({
                        "font-weight": "normal"
                    });
                    input.attr("data-bold", 0);
                    $(this).removeClass("active");
                } else {
                    input.css({
                        "font-weight": "bold"
                    });
                    input.attr("data-bold", 1);
                    $(this).addClass("active");
                }
            });

            that.dom.proTool.delegate("#pro-font-itilic", "click", function (e) {
                e.preventDefault();
                var input = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-text.active").first()
                        .find("textarea").first();
                if ($(this).hasClass("active")) {
                    input.css({
                        "font-style": "normal"
                    });
                    input.attr("data-italic", 0);
                    $(this).removeClass("active");
                } else {
                    input.css({
                        "font-style": "italic"
                    });
                    input.attr("data-italic", 1);
                    $(this).addClass("active");
                }
            });

            that.dom.proTool.delegate("#pro-font-size", "change", function (e) {
                var input = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-text.active").first()
                        .find("textarea").first();

                var val = $(this).val();
                input.css({
                    "font-size": val + "px"
                });
                input.attr("data-size", val);
            });

            that.dom.proTool.delegate("#pro-font-agile-left", "click", function (e) {
                e.preventDefault();
                var input = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-text.active").first()
                        .find("textarea").first();
                input.css({
                    "text-align": "left"
                });
                input.attr("data-align", "0");
                that.dom.proTool.find("#pro-font-agile-center, #pro-font-agile-right").removeClass("active");
                $(this).addClass("active");
            });

            that.dom.proTool.delegate("#pro-font-agile-center", "click", function (e) {
                e.preventDefault();
                var input = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-text.active").first()
                        .find("textarea").first();
                input.css({
                    "text-align": "center"
                });
                input.attr("data-align", "1");
                that.dom.proTool.find("#pro-font-agile-left, #pro-font-agile-right").removeClass("active");
                $(this).addClass("active");
            });

            that.dom.proTool.delegate("#pro-font-agile-right", "click", function (e) {
                e.preventDefault();
                var input = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-text.active").first()
                        .find("textarea").first();
                input.css({
                    "text-align": "right"
                });
                input.attr("data-align", "2");
                that.dom.proTool.find("#pro-font-agile-center, #pro-font-agile-left").removeClass("active");
                $(this).addClass("active");
            });

            that.dom.proTool.delegate(".btn-font", "click", function (e) {
                e.preventDefault();
                if ($(this).hasClass("active")) {
                    $(this).parent().children(".pro-font").addClass("hide");
                    $(this).removeClass("active");
                } else {
                    $(this).parent().children(".pro-font").removeClass("hide");
                    $(this).addClass("active");
                }
            });

            that.dom.proTool.delegate(".btn-reset", "click", function (e) {
                e.preventDefault();
                if (confirm("Bạn chắc chắn muốn thiết kế lại?")) {
                    that.dom.canvas.find(".design-panel").find("div").remove();
                }
            });

            that.dom.proTool.delegate(".btn-flip-w", "click", function (e) {
                e.preventDefault();
                var item = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-item.active").first();
                if (item.hasClass("import-text")) {
                    var area = item.find("textarea").first();
                    if (area.hasClass("flip-w")) {
                        area.removeClass("flip-w");
                    } else if (area.hasClass("flip-h")) {
                        area.removeClass("flip-h").addClass("flip-w-h");
                    } else if (area.hasClass("flip-w-h")) {
                        area.removeClass("flip-w-h").addClass("flip-h");
                    } else {
                        area.addClass("flip-w");
                    }
                } else if (item.hasClass("import-img")) {
                    var img = item.find("img").first();
                    if (img.hasClass("flip-w")) {
                        img.removeClass("flip-w");
                    } else if (img.hasClass("flip-h")) {
                        img.removeClass("flip-h").addClass("flip-w-h");
                    } else if (img.hasClass("flip-w-h")) {
                        img.removeClass("flip-w-h").addClass("flip-h");
                    } else {
                        img.addClass("flip-w");
                    }
                }
            });

            that.dom.proTool.delegate(".btn-flip-h", "click", function (e) {
                e.preventDefault();
                var item = that.dom.canvas.find(".design-panel.active").first()
                        .find(".import-item.active").first();
                if (item.hasClass("import-text")) {
                    var area = item.find("textarea").first();
                    if (area.hasClass("flip-h")) {
                        area.removeClass("flip-h");
                    } else if (area.hasClass("flip-w")) {
                        area.removeClass("flip-w").addClass("flip-w-h");
                    } else if (area.hasClass("flip-w-h")) {
                        area.removeClass("flip-w-h").addClass("flip-w");
                    } else {
                        area.addClass("flip-h");
                    }
                } else if (item.hasClass("import-img")) {
                    var img = item.find("img").first();
                    if (img.hasClass("flip-h")) {
                        img.removeClass("flip-h");
                    } else if (img.hasClass("flip-w")) {
                        img.removeClass("flip-w").addClass("flip-w-h");
                    } else if (img.hasClass("flip-w-h")) {
                        img.removeClass("flip-w-h").addClass("flip-w");
                    } else {
                        img.addClass("flip-h");
                    }
                }
            });

            that.dom.btnAddCart.on("click", function (e) {
                e.preventDefault();

                var url = $(this).attr("href");

                var data;
                data = new FormData();

                var sizeId = that.dom.proInfo.find("ul.pro-size").first().find("li.selected").first().attr("data-id");
                data.append("sizeId", sizeId);

                var i = 1;

                that.dom.canvas.find(".import-item").removeClass("active");
                that.dom.canvas.children().each(function () {
                    var el = this;
                    var isShow = $(el).hasClass("active");
                    if (!isShow) {
                        $(el).addClass("active");
                    }
                    html2canvas(this, {
                        onrendered: function (canvas) {
                            var file = canvas.toDataURL("image/png");//để mã hóa sẽ load chậm
//                            data.append("img" + i, file.replace('data:image/png;base64,', ''));
                            data.append("img" + i, file);
                            i++;
                            if (!isShow) {
                                $(el).removeClass("active");
                            }
                            if (i === 5) {
                                $.ajax({
                                    url: url,
                                    type: "POST",
                                    data: data,
                                    processData: false,
                                    contentType: false,
                                    dataType: "json",
                                    success: function (response) {
                                        if (response.status) {
                                            window.location.href = response.url;
                                        } else {
                                            alert(response.msg);
                                        }
                                    }
                                });
                            }
                        }
                    });
                });

            });

            /* Load data */
            that.dom.itemTool.find("form").submit();
            that.dom.productTool.find("form").submit();

            /* Trạng thái hiển thị mặc định */
            that.dom.productTool.addClass("active");
            that.dom.btnProduct.addClass("active");
        },
        createCanvas: function (callback) {
            var that = this;
            var draw = undefined;
            if (typeof (that.dom.draw) === "function") {
                draw = that.dom.draw();
            } else {
                draw = that.dom.draw;
            }

            html2canvas(draw, {
                onrendered: function (canvas) {
                    callback(canvas);
                    //$("body").append(canvas);
                }
            });
        },
        itemInitHandle: function (obj) {
            var that = this;
            $(obj).draggable({
                containment: "parent",
                cursor: "move",
                handle: ".ui-draggable", //cho phép di chuyển cả hình
                distance: 0,
                opacity: 0.85,
                scroll: false
            });

            $(obj).resizable({
                aspectRatio: true,
                containment: "parent",
                distance: 0,
                handles: "n, e, s, w"
            });
            $(obj).delegate(".btn-remove", "click", function (e) {
                e.preventDefault();
                //Trừ giá tiền của item này
                var itemPrice = parseFloat($(obj).attr("price"));
                //Caculate price
                var curPrice = parseFloat($("#price").attr("price"));
                var price = curPrice - itemPrice;
                $("#price").attr("price", price);
                $("#price").text(price.formatMoney(0, ',', '.'));

                obj.remove();
            });
        },
        textInitHandle: function (obj) {
            var that = this;
            $(obj).draggable({
                containment: "parent",
                cursor: "move",
                distance: 0,
                handles: ".btn-drag",
                opacity: 0.85,
                scroll: false
            });

            $(obj).resizable({
                containment: "parent",
                distance: 0,
                handles: "n, e, s, w"
            });

            $(obj).delegate(".btn-remove", "click", function (e) {
                e.preventDefault();
                obj.remove();
            });
        }
    };

    $(document).ready(function () {
        var panel = $("#design-wrapper");
        if (panel.length > 0) {
            $.design = new design();
            $.design.init(panel);
        }
    });
//Ext format price
    Number.prototype.formatMoney = function (c, d, t) {
        var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
        return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
    };
})(jQuery, document);